﻿using Farming.Application.Traceabilities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using QRCoder;
using System.Drawing;

namespace Farming.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class QRCoderController : ControllerBase
    {
        private readonly TraceabilityDataService traceabilitySev;
        public QRCoderController(TraceabilityDataService traceabilitySev)
        {
            this.traceabilitySev = traceabilitySev;
        }
        [HttpGet("generate-qr")]
        public async Task<IActionResult> GenerateQrCode()
        {
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                var exam1 = await traceabilitySev.GetTraceabilities();
                string exam2 = "asd";
                QRCodeData qrCodeData = qrGenerator.CreateQrCode($"{JsonConvert.SerializeObject(exam1)}{exam2}", QRCodeGenerator.ECCLevel.M);
                //QRCodeData qrCodeData = qrGenerator.CreateQrCode("https://www.doubao.com/chat/189549977821698", QRCodeGenerator.ECCLevel.M);
                using (QRCode qrCode = new QRCode(qrCodeData))
                {
                    using (Bitmap qrCodeImage = qrCode.GetGraphic(15))
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            qrCodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            return File(ms.ToArray(), "img/jpg", "qrcode.jpg");
                        }
                    }
                }
            }
        }

    }
}
